package spring_Proxydemo1.Proxydemo2;

import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.cglib.proxy.Proxy;

import java.lang.reflect.Method;

//动态代理:有jdk代理和cglib代理
//目前使用的是jdk代理:必须使用的是一个Factory工厂
public class ProxyDynamicFactory {
    private goalImpl target;

    public ProxyDynamicFactory() {
    }

    public ProxyDynamicFactory(goalImpl target) {
        this.target = target;
    }
    public Object getProxy(){
        //ClassLoader classLoader = this.getClass().getClassLoader();
       // ClassLoader classLoader = ProxyDynamicFactory.class.getClassLoader();
       ClassLoader classLoader = this.getClass().getClassLoader();
        Class<?>[] interfaces = target.getClass().getInterfaces();
      /*  InvocationHandler h =new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {

                Object result = method.invoke(target, objects);
                return result;
            }
        };
        return Proxy.newProxyInstance(classLoader,interfaces,h);
    }*/
        //lambda表达式优化
        InvocationHandler h =(Object o, Method method, Object[] objects)->{
            Object result = null;
            try {
                System.out.println("目标方法前");
                result = method.invoke(target, objects);
                System.out.println("目标方法后");
            } catch (Exception e) {
                System.out.println(e);
            }  finally {
                System.out.println("执行完毕");
            }
            return result;
        };
        return Proxy.newProxyInstance(classLoader,interfaces,h);
    }
}
